package com.example;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @author Create By Liuqz
 * @date 2018/11/16 11:21
 */
public class StreamFind {

    public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7,8,9});

        //findAny 方法返回的是最快处理完的那个线程的数据. 在对数据没有顺序上的要求, findAny比findFirst效率快
        Optional<Integer> optional1 = stream.filter(i -> i % 2 == 0).findAny();

        System.out.println(optional1.get());

        stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7,8,9});

        Optional<Integer> optional2 = stream.filter(i -> i > 7).findFirst();

        optional2.ifPresent(System.out::println);

        System.out.println(optional2.orElse(-1));


    }


    private static int find(Integer[] values, int defaultValue, Predicate<Integer> predicate) {
        for (Integer value : values) {
            if (predicate.test(value)) {
                return value;
            }
        }
        return defaultValue;
    }
}
